<template>
  <MesBox
    :modelValue="ttitle ? vvisble : visible"
    :title="ttitle || title"
    :height="400"
    :onModelClose="onModelClose"
  >
    <div class="outline_dash">
      <el-button type="default" @click="chooseFiles"> 选择文件</el-button>
      <el-button type="primary" @click="downloadTemplate">
        <i class="el-icon-download"></i>
        下载模板</el-button
      >
      <el-button type="success" @click="importBOM">
        <i class="el-icon-upload"></i>
        上传文件
      </el-button>

      <el-alert
        title="上传说明"
        type="warning"
        description="只能上传excel文件,文件大小不超过100M"
        show-icon
        :closable="false"
        style="margin-top: 10px"
      />

      <div class="files" v-if="fileList.name">
        <h3>文件列表</h3>
        <div class="file">
          <span class="filename">文件名：{{ fileList.name }}</span>
          <span class="filesize"
            >文件大小：{{
              parseInt((fileList.size / 1024) * 100) / 100
            }}kb</span
          >
        </div>
      </div>
      <div class="error" v-if="errorStr">{{ errorStr }}</div>
    </div>

    <template #footer>
      <el-button type="danger" @click="close">
        <i class="el-icon-close"></i>
        关闭
      </el-button>
    </template>
  </MesBox>
</template>

<script setup>
import MesBox from '@/components/basic/MesBox.vue'
import { ref, getCurrentInstance, toRefs, onMounted } from 'vue'

let props = defineProps({
  title: {
    type: String,
    default: '导入',
  },
  visible: {
    type: Boolean,
    default: false,
  },
  url: {
    type: String,
    default: '',
  },
})

let { title, visible, url } = toRefs(props)
let emit = defineEmits(['update:visible', 'refresh', 'handleClose', 'parentCall'])

let that = getCurrentInstance().appContext.config.globalProperties
let fileList = ref({})
let errorStr = ref('')
//选择文件
const chooseFiles = () => {
  let outline_dash = document.querySelector('.outline_dash')
  let input = document.createElement('input')
  input.type = 'file'
  input.style.display = 'none'
  input.setAttribute('accept', '.xls,.xlsx')
  outline_dash.appendChild(input)
  input.click()
  input.addEventListener('change', function (e) {
    let fileEl = e.target.files[0]
    let arr = fileEl.name.split('.')
    let suffix = arr[arr.length - 1]
    if (suffix == 'xls' || suffix == 'xlsx') {
      fileList.value = fileEl
      errorStr.value = ''
    } else {
      fileList.value = {}
      errorStr.value = '请选择文件类型为XLS或者XLSX为后缀名的文件'
    }
  })
}

// 下载导入模板
const downloadTemplate = () => {
  let outline_dash = document.querySelector('.outline_dash')
  let a = document.createElement('a')
  let name = ttitle.value || title.value
  // console.log(name);
  a.download = name + '模板.xlsx'
  a.style.display = 'none'
  a.href = '/' + name + '模板.xlsx'
  console.log(a.href)
  outline_dash.appendChild(a)
  a.click()
  outline_dash.removeChild(a)
}

//关闭
let close = () => {
  emit('update:visible', false)
  if (ttitle) {
    vvisble.value = false
  }
}

//监听用户是否选择过文件
window.onfocus = function () {
  let outline_dash = document.querySelector('.outline_dash')
  let input
  if (outline_dash) input = outline_dash.querySelector('input[type=file]')
  if (input) outline_dash.removeChild(input)
}

//导入
const importBOM = async () => {
  try {
    if (fileList.value.name) {
      let file = new FormData()
      if (ttitle.value) file.append('fileInput', fileList.value)
      else file.append('file', fileList.value)

      let res = await that.http.post(
        ttitle.value ? uurl : url.value,
        file,
        true
      )
      console.log(res)
      if (res.status) {
        that.$message.success('导入成功')
        emit('update:visible', false)
        emit('refresh')
        errorStr.value = ''
        fileList.value = ''
      } else {
        errorStr.value = res.message
      }
    } else {
      that.$message.error('请先选择文件然后再进行导入操作')
    }
  } catch (err) {
    console.log(err)
  }
}

const onModelClose = () => {
  if (ttitle.value == '') {
    emit('handleClose')
  } else {
    vvisble.value = false
  }
}

//通过调用函数传值
let ttitle = ref('')
let vvisble = ref(false)
let uurl = ''
const open = (title, url) => {
  ttitle.value = title
  uurl = url
  vvisble.value = true
}

defineExpose({ open, close, importBOM, onModelClose })
</script>

<style lang="less" scoped>
.outline_dash {
  height: 320px;
  padding: 10px;
  border: 1px dashed #ccc;
  border-radius: 10px;

  .filesize {
    margin-left: 10px;
  }
}

.error {
  color: red;
}
</style>
